package com.wjk.kylin.mall.gateway.handler;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.wjk.kylin.mall.common.core.constant.Constants;
import com.wjk.kylin.mall.common.core.dto.base.DataOutDTO;
import com.wjk.kylin.mall.common.redis.utils.RedisUtil;
import com.wjk.kylin.mall.gateway.config.CaptchaConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.annotation.Nonnull;
import java.awt.*;
import java.util.Map;

/**
 * 验证码获取
 *
 * @author ruoyi
 */
@Component
public class ValidateCodeHandler implements HandlerFunction<ServerResponse> {
    @Autowired
    private CaptchaConfig captchaConfig;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Mono<ServerResponse> handle(ServerRequest request) {
        DataOutDTO<Object> outDTO;
        try {
            //生成验证码
            CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(111, 36,5,0);
            captcha.setBackground(Color.gray);

            String code = captcha.getCode();
            String imageBase64 = captcha.getImageBase64();

            String uuid = IdUtil.simpleUUID();
            // 唯一标识
            String verifyKey = Constants.ADMIN_CAPTCHA_CODE_KEY + uuid;
            redisUtil.set(verifyKey, code, Constants.CAPTCHA_EXPIRATION);

            Map<String, Object> map = MapUtil.newHashMap(2);
            map.put("uuid", uuid);
            map.put("img", imageBase64);
            map.put("captchaOnOff", captchaConfig.getEnabled());
            outDTO = DataOutDTO.builder().data(map).build();
        } catch (Exception e) {
            return Mono.error(e);
        }
        return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(outDTO));
    }
}